import { Message } from 'element-ui'
/**
 * @description 错误弹窗
 */
export const errorMessage = (message: string) => Message({
  message,
  type: 'error',
  duration: 3000
})

export const networkError = () => {
  // 让网络异常弹窗不要多次重复弹出，大约3.5s内只弹出一次
  const now = +new Date();
  const networkErrorTime = localStorage.getItem('networkErrorTime');
  if (networkErrorTime) {
    if (now > +networkErrorTime + 3500) {
      // 写成3500是考虑到弹窗计时器的延时可能滞后的情况
      errorMessage("网络异常，请检查网络");
      localStorage.setItem('networkErrorTime', now + '');
    }
  } else {
    errorMessage("网络异常，请检查网络");
    localStorage.setItem('networkErrorTime', now + '');
  }
}

export function removeLeaf(arr: Array<any>, key = 'children') {
  // 去除多余的叶子节点
  return arr.map((e) => {
    if (e[key]) {
      if (e[key].length == 0) {
        delete e[key];
      } else {
        e[key] = removeLeaf(e[key], key);
      }
    }
    return e;
  });
}

/**
 * @description 生成一个计数函数，该计数函数每在指定的延时内触发一次，内部计数加1，当计数达到目标值则返回true，若不在延时内触发，则内部计数重置为0
 * @param target 目标次数
 * @param delay 每次触发之间允许的延时
 * @returns {boolean} 是否已经达到目标值
 */
export const DelayCounter = (target = 5, delay = 1000) => {
  let count = 1, timer: number | null = null;
  return () => {
    // console.log(count);
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      count = 1;
    }, delay);
    if (count >= target) {
      count = 1;
      return true;
    } else {
      count++;
      return false;
    }
  }
}


// 将base64转换为blob
const dataURLtoBlob = (dataurl) => {
  const arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

// 将blob转换为file
const blobToFile = (theBlob, fileName) => {
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return new File([theBlob], `${fileName}.${theBlob.type.split('/')[1]}`, { type: theBlob.type });
}

export const imgUrlToFile = (imgBase64: string) => {
  return new Promise((resolve, reject) => {
    const blob = dataURLtoBlob(imgBase64);
    const file = blobToFile(blob, 'screenShot');
    resolve(file);
  })
}